package com.iot.ic.tcp.netty;

import com.iot.ic.tcp.coder.CustomDecoder;
import com.iot.ic.tcp.coder.CustomEncoder;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

//ChannelInitializer是默认的initializer，因此需要继承ChannelInitializer类来实现自己的initializer
@Component("customChannelInitializer")
public class CustomChannelInitializer extends ChannelInitializer<SocketChannel> implements ApplicationContextAware {
	
	// The spring application context.
    private static ApplicationContext applicationContext;
    @Autowired
    private CustomHandler customHandler;
	
	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		
		// 添加到pipeline中的handler会被串行处理(PS: 类似工业生产中的流水线)
		ChannelPipeline pipeline = ch.pipeline();
		/*
		 * pipeline.addLast("idleStateCheck", new IdleStateHandler(
		 * MAX_IDLE_SECONDS, MAX_IDLE_SECONDS, MAX_IDLE_SECONDS));
		 */

		// 使用addLast来添加自己定义的handler到pipeline中
		// pipeline.addLast("multiplexer", createMyProtcolDecoder());
		//ch.pipeline().addLast(new IdleStateHandler(0, 0, 10));
		//ch.pipeline().addLast("frameDecoder", new LengthFieldBasedFrameDecoder(65535, 0, 2, 0, 2));
		ch.pipeline().addLast("msgDecoder", new CustomDecoder());
		//ch.pipeline().addLast("frameEncoder", new LengthFieldPrepender(2));
		ch.pipeline().addLast("msgEncoder", new CustomEncoder());
		ch.pipeline().addLast(customHandler);
	}

	@Override
	public void setApplicationContext(ApplicationContext applicationContext)
            throws BeansException
    {
		CustomChannelInitializer.applicationContext = applicationContext;
    }

}